/* ------------------------------------------ 业务相关工具类 ------------------------------------------ */

import { idCard as valiIdcard } from "./validator";
import { strToDate, dateToStr } from "./format";

/**
 * 根据身份证获取个人信息：城市code，出生日期，性别
 * @param {*} idcard 身份证号
 */
export const getPersonInfoByIdcard = idcard => {
  // 身份证校验不通过，不处理，返回false
  if (!valiIdcard(idcard)) return false;

  let sex =
    idcard.length == 15 ? idcard.substr(14, 1) % 2 : idcard.substr(16, 1) % 2;
  sex == 0 ? (sex = 2) : (sex = 1);
  let birthday =
    idcard.length == 15
      ? "19" +
        idcard.substr(6, 2) +
        "-" +
        idcard.substr(8, 2) +
        "-" +
        idcard.substr(10, 2)
      : idcard.substr(6, 4) +
        "-" +
        idcard.substr(10, 2) +
        "-" +
        idcard.substr(12, 2);
  //增加年龄校验 出生日期不能大于当前日期
  return {
    cityCode: idcard.substr(0, 4),
    birthday,
    sex
  };
};

/**
 * 获取基于baseDay前XX天或后XX天的日期对象与对应的字符串
 * @param {*} baseDay 基准日期，可传字符串格式 || date对象
 * @param {*} offset 偏移量，单位为天，可传小数和负数
 */
export const dayAfter = (baseDay = new Date(), offset = 1) => {
  // 一天的时间戳
  const aDayTs = 24 * 60 * 60 * 1000;
  // 总共偏移的时间戳
  const offsetDayTs = offset * aDayTs;

  // 处理baseDay为字符串的情况
  if (typeof baseDay === "string") {
    baseDay = strToDate(baseDay);
  }

  // 偏移后的时间戳
  const afterDayTs = baseDay.getTime() + offsetDayTs;
  // 偏移后的日期对象
  const afterDay = new Date(afterDayTs);

  // 返回date和date对应的字符串
  return {
    date: afterDay,
    str: dateToStr(afterDay, "yyyy-MM-dd")
  };
};

const business = {
  getPersonInfoByIdcard,
  dayAfter
};

export default business;
